#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 100

int main(void) {
    FILE *readfp, *writefp;
    char buf[BUFFER_SIZE];

    // 打开读取进程（ps aux）
    if ((readfp = popen("ps aux", "r")) == NULL) {
        perror("popen(ps) failed");
        exit(EXIT_FAILURE);
    }

    // 打开写入进程（grep init）
    if ((writefp = popen("grep init", "w")) == NULL) {
        perror("popen(grep) failed");
        pclose(readfp);  // 关闭已打开的管道
        exit(EXIT_FAILURE);
    }

    // 管道数据中转
    while (fgets(buf, BUFFER_SIZE, readfp) != NULL) {
        if (fputs(buf, writefp) == EOF) {
            perror("fputs failed");
            break;
        }
    }

    // 关闭管道并回收子进程
    int status_ps = pclose(readfp);
    int status_grep = pclose(writefp);

    // 验证子进程退出状态
    if (WIFEXITED(status_ps)) {
        printf("ps exited with status %d\n", WEXITSTATUS(status_ps));
    }
    if (WIFEXITED(status_grep)) {
        printf("grep exited with status %d\n", WEXITSTATUS(status_grep));
    }

    return EXIT_SUCCESS;
}
